//
//  EJCommentInputView.m
//  EJCommentKit_Example
//
//  Created by ejiang on 2021/11/29.
//  Copyright © 2021 15093319898@163.com. All rights reserved.
//

#import "EJCommentInputView.h"
#import <EJTools/EJProgressHUD.h>
//#import <UITextView+Placeholder/UITextView+Placeholder.h>
#import "UITextView+Placeholder.h"

@interface EJCommentInputView ()<UITextViewDelegate>

@property (nonatomic, assign) EJ_Comment_WordLimitType wordLimitType;

@end

@implementation EJCommentInputView

@synthesize lineColor = _lineColor;
@synthesize textColor = _textColor;
@synthesize placeholder = _placeholder;
@synthesize tintColor = _tintColor;
@synthesize textBgColor = _textBgColor;
@synthesize font = _font;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _wordLimitType = EJ_Comment_WordLimitType_None;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapCommentBg)];
        [self addGestureRecognizer:tap];
        [self addSubview:self.commentBar];
        
        _commentBar.frame = CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds), frame.size.width, 51);
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (instancetype)initWithWordLimitType:(EJ_Comment_WordLimitType)wordLimitType maxCount:(NSInteger)maxCount {
    self = [super initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds))];
    if (self) {
        _wordLimitType = wordLimitType;
        _maxCount = maxCount;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapCommentBg)];
        [self addGestureRecognizer:tap];
        [self addSubview:self.commentBar];
        
        _commentBar.frame = CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds), CGRectGetWidth([UIScreen mainScreen].bounds), 51);
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (void)beginOnceInput {
    [self.commentBar becomeFirstResponder];
}

- (void)completeOnceInput {
    self.commentBar.textView.text = nil;
    [self.commentBar.textView resignFirstResponder];
    [self removeFromSuperview];
}

#pragma mark - action
- (void)handleTapCommentBg {
    _commentBar.textView.text = nil;
    [_commentBar.textView resignFirstResponder];
    [self removeFromSuperview];
}

- (void)handleClickCommentBar {
    
}

- (void)handleClickSendButton:(UIButton *)sender {
    NSString * content = [_commentBar.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([content length] == 0) {
        [EJProgressHUD showAlert:@"请输入有效评论" forView:[UIApplication sharedApplication].delegate.window];
        return;
    }
    sender.enabled = NO;
    if ([self.delegate respondsToSelector:@selector(ej_commentInputViewDidClickSendWithContent:)]) {
        [self.delegate ej_commentInputViewDidClickSendWithContent:_commentBar.textView.text];
    }
    sender.enabled = YES;
    [self completeOnceInput];
}

- (void)handleKeyboardWillChange:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect endFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    
    CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    CGRect frame = _commentBar.frame;
    if (endFrame.origin.y == screenHeight) {
        frame.origin.y = screenHeight - CGRectGetHeight(frame);
    } else {
        frame.origin.y = screenHeight - CGRectGetHeight(endFrame) - CGRectGetHeight(frame);
    }
    
    __weak typeof(self) weak_self  = self;
    [UIView animateWithDuration:duration delay:0.f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:^{
        weak_self.commentBar.frame = frame;
    } completion:nil];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    CGRect frame = _commentBar.frame;
    frame.size.height = 51;
    _commentBar.frame = frame;
}

- (void)textViewDidChange:(UITextView *)textView {
    // 计算高度
    CGSize size = [textView sizeThatFits:CGSizeMake(CGRectGetWidth(self.frame) - 14 - 62 - 30, MAXFLOAT)];
    CGFloat height = ceil(size.height);
    if (height <= 51) {
        textView.scrollEnabled = NO;
    } else {
        textView.scrollEnabled = YES;
    }
    height = height > 51 ? 51 : height;
    height = height < 36 ? 36 : height;
    
    CGRect frame = _commentBar.frame;
    CGFloat maxY = CGRectGetMaxY(frame);
    frame.size.height = height + 15;
    frame.origin.y = maxY - CGRectGetHeight(frame);
    _commentBar.frame = frame;
    
    if (_wordLimitType == EJ_Comment_WordLimitType_None) {
        if (textView.text.length > 0) {
            _commentBar.sendButton.enabled = YES;
        } else {
            _commentBar.sendButton.enabled = NO;
        }
        return;
    }
    
    //当前输入语言状态
    UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
    NSString *lang = mode.primaryLanguage;
    
    //汉字
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textView markedTextRange];
        //高亮状态的start位置
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        
        //没有高亮状态，即每次截取要在文字确认之后
        if (!position) {
            
            if (textView.text.length > _maxCount) {
                textView.text = [textView.text substringToIndex:_maxCount];
                if (_wordLimitType == EJ_Comment_WordLimitType_Alert) {
                    [EJProgressHUD showAlert:[NSString stringWithFormat:@"不能超过%d字", (int)_maxCount] forView:[UIApplication sharedApplication].delegate.window];
                }
            } else {
            }
        }
    }
    //非汉字状态
    else {
        if (textView.text.length > _maxCount) {
            textView.text = [textView.text substringToIndex:_maxCount];
            if (_wordLimitType == EJ_Comment_WordLimitType_Alert) {
                [EJProgressHUD showAlert:[NSString stringWithFormat:@"不能超过%d字", (int)_maxCount] forView:[UIApplication sharedApplication].delegate.window];
            }
        } else {
        }
    }
    NSString * content = [_commentBar.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (content.length > 0) {
        _commentBar.sendButton.enabled = YES;
    } else {
        _commentBar.sendButton.enabled = NO;
    }
}

#pragma mark - getter or setter
- (EJCommentBar *)commentBar {
    if (!_commentBar) {
        _commentBar = [[EJCommentBar alloc] init];
        _commentBar.textView.delegate = self;
        [_commentBar.sendButton addTarget:self action:@selector(handleClickSendButton:) forControlEvents:UIControlEventTouchUpInside];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleClickCommentBar)];
        [_commentBar addGestureRecognizer:tap];
    }
    return _commentBar;
}

- (void)setLineColor:(UIColor *)lineColor {
    self.commentBar.topLine.backgroundColor = lineColor;
}

- (UIColor *)lineColor {
    return self.commentBar.topLine.backgroundColor;
}

- (void)setTextColor:(UIColor *)textColor {
    self.commentBar.textView.textColor = textColor;
}

- (UIColor *)textColor {
    return self.commentBar.textView.textColor;
}

//- (void)setPlaceholderColor:(UIColor *)placeholderColor {
//    self.commentBar.textView.placeholderColor = placeholderColor;
//}

- (void)setPlaceholder:(NSAttributedString *)placeholder {
    self.commentBar.textView.attributedPlaceholder = placeholder;
}

- (NSAttributedString *)placeholder {
    return self.commentBar.textView.attributedPlaceholder;
}

- (void)setTintColor:(UIColor *)tintColor {
    self.commentBar.textView.tintColor = tintColor;
}

- (UIColor *)tintColor {
    return self.commentBar.textView.tintColor;
}

- (void)setTextBgColor:(UIColor *)textBgColor {
    self.commentBar.textView.backgroundColor = textBgColor;
}

- (UIColor *)textBgColor {
    return self.commentBar.textView.backgroundColor;
}

- (void)setFont:(UIFont *)font {
    self.commentBar.textView.font = font;
}

- (UIFont *)font {
    return self.commentBar.textView.font;
}

@end
